<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>
  let delegate = function (client, delegation) {
    return {
      buttonWasPressed: function () {
        return delegation.buttonWasPressed.apply(client, arguments);
      }
    }
  }

  let FSM = {
    off: {
      buttonWasPressed: function () {
        console.log("关灯");
        this.button.innerHTML = "下一次按我是开灯";
        this.currentState = this.onState;
      }
    },
    on: {
      buttonWasPressed: function () {
        console.log("开灯");
        this.button.innerHTML = "下一次按我是关灯";
        this.currentState = this.offState;
      }
    }
  }

  let Light = function () {
    this.offState = delegate(this, FSM.off);
    this.onState = delegate(this, FSM.on);
    this.currentState = this.offState;
    this.button = null;
  }

  Light.prototype.init = function () {
    let button = document.createElement("button");
    let self = this;

    button.innerHTML = "已关灯";
    this.button = document.body.appendChild(button);
    this.button.onclick = function () {
      self.currentState.buttonWasPressed();
    }
  }

  let light = new Light();
  light.init();
</script>

</html>